<?php
class PodcastReader
{
  private $url;
  private $channel_title;
  private $channel_link;
  private $items  = array();
  private $errors = array();
  private $xmlString;
  private $enclosure_types  = array('audio/mpeg','mp3','media/mpeg');
  private $item_limit = RSS_ITEMS;
  public function __construct($url,$init = TRUE)
  {
    $this->url = $url;
    if($init)
    {
      if($this->cacheIsTooOld())
      {
        if($this->xmlString = Tools::curl_content($url))
        {
          $this->stringToFile();
        }
        else
        {
          $this->xmlString = '';
        }
        $this->stringToFile();
      }
      $this->fileToString();
      $this->parseXmlString();
    }
  }
  
  public function delete()
  {
    $sql = "DELETE FROM podcast WHERE url='".sqlite_escape_string($this->url)."' AND usr_id='".$_SESSION['MczSession']->getLogin()."'";
    $dbh = new dbSql();
    $res = $dbh->exec($sql);
    return(self::getPodcasts());
  }
  
  public function insert()
  {
    if(empty($this->error) and !empty($this->url) and !empty($this->channel_title))
    {
      $sql="INSERT INTO podcast values('".$_SESSION['MczSession']->getLogin()."','".sqlite_escape_string($this->url)."','".sqlite_escape_string($this->channel_title)."',NULL)";
      $dbh = new dbSql();
      $dbh->exec($sql);
      return(self::getPodcasts());
    }
  }
  
  private function cacheIsTooOld()
  {
    $cache_file = DATA_PATH.'cache/'.md5($this->url);
    if(!is_file($cache_file))
    {
      return(TRUE);
    }
    if(filemtime($cache_file) < $_SERVER['REQUEST_TIME'] - RSS_TTL)
    {
      return(TRUE);
    }
    else
    {
      return(FALSE);
    }
  }
  
  private function fileToString()
  {
    $cache_file = DATA_PATH.'cache/'.md5($this->url);
    $this->xmlString = file_get_contents($cache_file);
  }
  
  private function stringToFile()
  {
    if(!is_dir(DATA_PATH.'cache'))
    {
      mkdir(DATA_PATH.'cache',0755,TRUE);
    }
    $cache_file = DATA_PATH.'cache/'.md5($this->url);
    file_put_contents($cache_file,$this->xmlString);
  }
  
  private function parseXmlString()
  {
    try
    {
      $xml = new SimpleXMLElement($this->xmlString);
      $this->channel_title = $xml->channel->title;
      $this->channel_link  = $xml->channel->link;
      $this->encoding  = (string)$xml->encoding;
      foreach ($xml->channel->item as $item)
      {
        if(isset($item->enclosure))
        {
          if(isset($item->enclosure->attributes()->type))
          {
            if(in_array(strtolower($item->enclosure->attributes()->type),$this->enclosure_types))
            {
              $this->items[] = array( 'description'=>(string)$item->description,
                                      'title'=>(string)$item->title,
                                      'url'=>(string)$item->enclosure->attributes()->url,
                                      'link'=>(string)$item->link);
            }
          }
        }
      }
    }
    catch(Exception $e)
    {
      $this->errors[] = STR_ERR_PODCAST_NOT_FOUND;
    }
  }
  
  public function mkHtml()
  {
    if(empty($this->errors))
    {
      $html = '<h2><a onmouseover="help(str.hlp_go_to_site);" href="'.$this->channel_link.'" target="_blank" onclick="openMczBrowser($(this).attr(\'href\'));return false;">'.$this->channel_title.'</a></h2>
              <ul class="podcastItems">';
      $i=0;
      $tr = 'row1';
      foreach($this->items as $item)
      {
        if($i > $this->item_limit)
        {
          break;
        }
        if($i%2)
        {
          $tr='row1';
        }
        else
        {
          $tr='row2';
        }
        if(!empty($item['description']))
        {
          $desc = '<div class="podDesc">'.$item['description'].'</div>';
        }
        else
        {
          $desc = '';
        }
        if($_SESSION['MczSession']->can('add_file'))
        {
          $addButton = '<input type="image" src="app/skin/transparent.gif" class="btnAddToCollection" onmouseover="help(str.hlp_add_to_collection);" onclick="addToLibrary(\''.$item['url'].'\');return false;"/>';
        }
        else
        {
          $addButton = '';
        }
        if(!empty($item['link']))
        {
          $titleItem = '<a onmouseover="help(str.hlp_go_to_site);" href="'.$item['link'].'" target="_blank">'.$item['title'].'</a>';
        }
        else
        {
          $titleItem = $item['title'];
        }
        
        $html.='<li class="'.$tr.'">
                  <h3><input type="image" src="app/skin/transparent.gif" class="btnAddToCue" onmouseover="help(str.hlp_add_to_cue);" onclick="addToCue(\'url\',\''.addslashes($item['title']).'\',\''.urlencode($item['url']).'\');return false;"/>
                  '.$addButton.'&nbsp;'.$titleItem.'
                  </h3>
                  '.nl2br($desc).'
                </li>';
        $i++;
      }
      $html.='</ul>';
      return($html);
    }
    else
    {
      return('<em>'.implode('/',$this->errors).'</em>');
    }
  }
  
  /**
   * return html select of podcasts
   * 
   * @return string      
   */   
  public static function getPodcasts()
  {
    $sql = "SELECT ucwords(low_case(title,'UTF-8')) as title,url FROM podcast WHERE usr_id='".$_SESSION['MczSession']->getLogin()."' ORDER BY low_case(title) ASC";
    $dbh = new dbSql();
    $dbh->registerFn('low_case','mb_strtolower');
    $dbh->registerFn('ucwords','ucwords');
    $res = $dbh->query($sql);
    if(empty($res))
    {
      return('<div class="errormsg"><input id="btnAddPodcast" onmouseover="help(str.hlp_add_podcast);" class="btnPodAdd" onclick="addPodcast();return false;" type="image" src="app/skin/transparent.gif" />&nbsp;'.STR_UI_EMPTY_LIST.'</div>');
    }
    $tab['empty']=STR_HLP_PODCASTS_LIST;
    foreach($res as $podcast)
    {
      $tab[$podcast['url']] = $podcast['title'];
    }
    $select = Html::mkSelect(array('labelLength'=>60,'script'=>'onchange="loadPodcast(this.value);" onmouseover="help(str.hlp_podcasts_list);"','id'=>'podcastsSelect','values'=>$tab));
    $html = '<input id="btnAddPodcast" onmouseover="help(str.hlp_add_podcast);" class="btnPodAdd" onclick="addPodcast();return false;" type="image" src="app/skin/transparent.gif" />&nbsp;'.$select.'&nbsp;<input id="btnDeletePodcast" class="btnPodRemove" onmouseover="help(str.hlp_delete_podcast);" onclick="deletePodcast($(\'#podcastsSelect\').val());return false;" type="image" src="app/skin/transparent.gif"/>';
    return($html);
  }
}
?>
